import datetime
import re
from settings import data2_connection, data1_connection
from pymysql.err import MySQLError


def str_time_to_time(str_time):
    """
    把字符串转换为时间
    :param str_time:
    :return:
    """
    date = datetime.datetime.strptime(str_time, "%Y-%m-%d")
    date = date.date()
    return date


def cookie_to_str(cookies):
    cookie_str = ""
    for cookie in cookies:
        cookie_str += cookie["name"] + "=" + cookie["value"] + ";"
    strip_cookie = cookie_str.strip(";")
    return strip_cookie


def time_to_str():
    """
    把当天的时间转换为字符串
    :param :
    :return:
    """
    today = datetime.datetime.strftime(datetime.date.today(), "%Y-%m-%d")
    return today


def get_data():
    data = {
        "undefined": "",
        "ajax": 1
    }
    return data


def time_stamp(stamp):
    """
    把时间戳转换为时间
    :param stamp:
    :return:
    """
    str_stamp = str(stamp)
    str_stamp = str_stamp[:-3]
    int_time = int(str_stamp)
    current_time = datetime.datetime.utcfromtimestamp(int_time)
    return current_time


def historical_transaction(data):
    first_list = data.split("\n")
    first_list.pop(0)
    first_list.pop()
    all_data_list = []
    for data in first_list:
        data_dict = {}
        data_list = data.split(",")
        if not data_list:
            continue
        print(data_list)
        data_dict["datetime"] = data_list[0] + " " + data_list[1] + ":" + "00"
        data_dict["type"] = data_list[2]
        data_dict["code"] = data_list[3]
        data_dict["transaction_type"] = data_list[4]
        data_dict["order_type"] = data_list[5]
        data_dict["clinch_a_deal_the_quantity"] = data_list[6]
        data_dict["clinch_a_deal_valence"] = data_list[7]
        data_dict["turnover"] = data_list[8]
        data_dict["unwinding_of_profit_and_loss"] = data_list[9]
        data_dict["poundage"] = data_list[10]
        data_dict["clinch_a_deal_the_state"] = data_list[11]
        data_dict["entrust_the_number"] = data_list[12]
        all_data_list.append(data_dict)
    return all_data_list


def get_stock(stock):
    """
    输入类似的字符串，返回code, name
    :return: code, name
    """
    str1 = stock.split("(")
    str2 = str1[1]
    str3 = str2.split(")")
    code = str3[0]
    codes = code.split(".")
    code = codes[0]
    name = str1[0]
    return name, code


def float_to_percentage(data):
    """
    把百分数转换为小数
    :param data:
    :return:
    """

    data = float(data) / 100
    return data


def get_strategy_position(data):
    """
    返回处理后的股票持仓数
    :param data: 100股
    :return:
    """
    number = re.findall(r"(\d+)", data)
    return int(number[0])


def get_backtest_id(url):
    """
    通过browser的目前所在的页面的url， 来得到backtest_id
    :param url:
    :return:str
    """
    backtest_id = url.split('=')
    return backtest_id[1]


def select_online_bench(date):
    """
    连接线上的数据库， 取出bench的数据
    :param date:
    :return:
    """
    cursor, conn = data2_connection()
    sql = "select `close` from hs300 where date='%s'" % date
    try:
        cursor.execute(sql)
        conn.commit()
        data = cursor.fetchall()
        if data:
            bench = data[0]["close"]
            return bench
        else:
            return None
    except MySQLError as e:
        print("数据线上数据获取失败%s" % e)
        return None


def select_online_open(date):
    """
    连接线上的数据库， 取出开盘价open
    :param date:
    :return:
    """
    cursor, conn = data2_connection()
    sql = "select `open` from hs300 where `date`='%s'" % date
    try:
        cursor.execute(sql)
        conn.commit()
        data = cursor.fetchall()
        if data:
            open = data[0]["open"]
            return open
        else:
            return None
    except MySQLError as e:
        print(e)
        return None


def get_trade_number(str_number):
    """
    example:<span class='sell'>-1100股</span>
    return : 1100
    :param str_number:
    :return:
    """
    data = re.findall(r'(\d+)', str_number)
    trade_number = int(data[0])
    return trade_number


def percentage_to_float(number):
    """
    把百分数转换为小数
    :param number:
    :return:
    """
    data = float(number.strip("%")) / 100
    return data


def get_real_capital(number):
    """
    把￥800.00转换成 800.00
    :param number:
    :return:
    """
    number = number.strip("¥")
    number = number.replace(",", "")
    number = float(number)
    return number


def get_code_close(code, trade_time):
    """
    获取当前时间的code的收盘价
    :param code:
    :return:
    """
    cursor, conn = data2_connection()
    sql = "select `close` from `%s` where datetime='%s'" % (code, trade_time)
    try:
        cursor.execute(sql)
        conn.commit()
        data = cursor.fetchall()
        if data:
            close = data[0]["close"]
            return close
        else:
            return None
    except MySQLError as e:
        print(e)
        conn.rollback()


def get_accumuReturn_indexReturn_data_list(data_list):
    """
    把查询数据库返回的数据， 转换为相应的列表， 再返回列表中的最大值
    :param data_list:
    :return:
    """
    accmu_reutrn_list = []
    index_return_list = []
    for data in data_list:
        accmuReutrn = data["accumuReturn"]
        indexReturn = data["indexReturn"]
        accmu_reutrn_list.append(accmuReutrn)
        index_return_list.append(indexReturn)
    max_accumu_return = max(accmu_reutrn_list)
    max_index_return = max(index_return_list)
    print("策略收益最大值%s：" % max_accumu_return)
    print("指数收益最大值%s:" % max_index_return)
    return max_accumu_return, max_index_return


def select_before_down(backtestId, date):
    """
    获取历史的最大的值百分比
    :param backtestId:
    :param date:
    :return:
    """
    cursor, conn = data1_connection()
    sql = "select accumuReturn, indexReturn from strategy_backtest_netvalue where dateTime < '%s' " \
          "and backtestId='%s'"
    end_sql = sql % (date, backtestId)
    try:
        cursor.execute(end_sql)
        conn.commit()
        data_list = cursor.fetchall()
        if data_list:
            max_accmu_return, max_index_return = get_accumuReturn_indexReturn_data_list(data_list)
            return max_accmu_return, max_index_return
        else:
            return 0, 0
    except MySQLError as e:
        print(e)
    conn.rollback()




